<template>
	<div class="report-page" style="padding: 20px">
		<!-- 顶部操作栏 -->
		<div class="toolbar">
			<el-radio-group v-model="activeType" size="small">
				<el-radio-button label="电" />
				<el-radio-button label="水" />
				<el-radio-button label="气" />
			</el-radio-group>

			<el-radio-group v-model="timeMode" size="small" style="margin-left: 10px">
				<el-radio-button label="日" />
				<el-radio-button label="周" />
				<el-radio-button label="月" />
			</el-radio-group>

			<el-button size="small" type="primary" style="margin-left: auto" @click="exportExcel">导出 Excel</el-button>
			<el-button size="small" type="success" @click="exportImage">导出图片</el-button>
		</div>

		<!-- 饼图展示 -->
		<v-chart ref="chartRef" :option="chartOptions" style="height: 320px;" />

		<!-- 数据表格 -->
		<el-table :data="tableData" stripe style="margin-top: 20px;">
			<el-table-column prop="type" label="设备类型" width="120" />
			<el-table-column prop="usage" label="用量" width="120" />
			<el-table-column prop="unit" label="单位" width="80" />
			<el-table-column prop="rate" label="占比" width="100" />
			<el-table-column prop="total" label="总数" width="100" />
			<el-table-column prop="normal" label="正常" width="100" />
			<el-table-column prop="abnormal" label="异常" width="100" />
		</el-table>
	</div>
</template>

<script setup>
import { ref, computed, watchEffect } from 'vue'
import VChart from 'vue-echarts'
import html2canvas from 'html2canvas'
import * as XLSX from 'xlsx'
import { ElMessage } from 'element-plus'

const chartRef = ref(null)
const timeMode = ref('日')
const activeType = ref('电')

const deviceTypeMap = {
	电: ['空调', '照明', '电梯', '新风', '插座'],
	水: ['洗手间', '饮水机', '加湿器'],
	气: ['锅炉', '燃气灶', '热水器']
}
const unitMap = {
	电: 'kWh',
	水: 'm³',
	气: 'm³'
}
const tableData = ref([])

function generateData() {
	const types = deviceTypeMap[activeType.value]

	let baseUsage, usageRange, totalBase, totalRange
	if (timeMode.value === '日') {
		baseUsage = 80
		usageRange = 40
		totalBase = 10
		totalRange = 10
	} else if (timeMode.value === '周') {
		baseUsage = 200
		usageRange = 100
		totalBase = 20
		totalRange = 20
	} else {
		baseUsage = 500
		usageRange = 300
		totalBase = 40
		totalRange = 20
	}

	const values = types.map(() => Math.round(baseUsage + Math.random() * usageRange))
	const sum = values.reduce((a, b) => a + b, 0)

	tableData.value = types.map((type, i) => {
		const usage = values[i]
		const total = Math.round(totalBase + Math.random() * totalRange)
		const abnormal = Math.round(Math.random() * 3)
		const normal = total - abnormal
		return {
			type,
			usage,
			unit: unitMap[activeType.value],
			rate: ((usage / sum) * 100).toFixed(1) + '%',
			total,
			normal,
			abnormal
		}
	})
}

watchEffect(generateData)

const chartOptions = computed(() => ({
	title: {
		text: `${activeType.value}设备占比（${timeMode.value}维度）`,
		left: 'center'
	},
	tooltip: { trigger: 'item' },
	legend: { bottom: 10, data: deviceTypeMap[activeType.value] },
	series: [
		{
			name: '能耗',
			type: 'pie',
			radius: '60%',
			data: tableData.value.map(d => ({
				name: d.type,
				value: d.usage
			}))
		}
	]
}))

function exportExcel() {
	const rows = [['设备类型', '用量', '单位', '占比', '总数', '正常', '异常']]
	for (const d of tableData.value) {
		rows.push([d.type, d.usage, d.unit, d.rate, d.total, d.normal, d.abnormal])
	}
	const ws = XLSX.utils.aoa_to_sheet(rows)
	const wb = XLSX.utils.book_new()
	XLSX.utils.book_append_sheet(wb, ws, '设备报表')
	XLSX.writeFile(wb, `设备报表_${activeType.value}_${timeMode.value}.xlsx`)
}

function exportImage() {
	const el = chartRef.value?.$el
	if (!el) return
	html2canvas(el).then(canvas => {
		const link = document.createElement('a')
		link.href = canvas.toDataURL()
		link.download = `设备能耗图_${activeType.value}_${timeMode.value}.png`
		link.click()
	}).catch(() => {
		ElMessage.error('导出失败')
	})
}
</script>

<style scoped>
.toolbar {
	display: flex;
	align-items: center;
	margin-bottom: 10px;
	gap: 10px;
}
</style>